package com.dingup.provider.controller.sys;

import com.alibaba.fastjson.JSONObject;
import com.dingup.api.Util.JwtTokenUtil;
import com.dingup.api.Util.PasswordUtil;
import com.dingup.api.Util.RedisUtils;
import com.dingup.api.Util.UuidUtil;
import com.dingup.api.adapter.user.SysUserAdapter;
import com.dingup.api.base.HttpResContent;
import com.dingup.api.bean.page.PageData;
import com.dingup.api.bean.response.SelectBean;
import com.dingup.api.model.sys.*;
import com.dingup.provider.mapper.DingtalkUserMapper;
import com.dingup.provider.mapper.SysUserBindInfoMapper;
import com.dingup.provider.mapper.SysUserMapper;
import com.dingup.provider.mapper.SysUserRoleMapper;
import com.dingup.provider.service.sys.LoadUserPermissionService;
import com.dingup.provider.service.sys.SysDeptService;
import com.dingup.provider.service.sys.SysUserService;
import com.suyeer.basic.util.BHttpResUtil;
import com.suyeer.basic.util.BJsonUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.dingup.api.base.BaseUtil.saveErrorMsgAndData;
import static com.dingup.api.base.BaseUtil.saveSuccessMsgAndData;
import static com.dingup.provider.util.ConstUtil.*;

/**
 * Created by wancheng on 2018/7/16.
 */
@RestController()
@RequestMapping("/user")
public class SysUserController {

    @Autowired
    SysUserMapper sysUserMapper;
    @Autowired
    SysUserService sysUserService;
    @Autowired
    SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    DingtalkUserMapper dingtalkUserMapper;
    @Autowired
    LoadUserPermissionService loadUserPermissionService;
    @Autowired
    SysDeptService deptService;
    @Autowired
    SysUserBindInfoMapper sysUserBindInfoMapper;

    @RequestMapping(value = "/list_all_user.do",method = RequestMethod.POST)
    public void listAllUser(HttpServletRequest request, HttpServletResponse response) {
        HttpResContent<List<SysUser>> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("获取用户列表");
        try {
            List<SysUser> list = sysUserMapper.listAllUser();
            saveSuccessMsgAndData(hrc, list);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/get_user_msg.do",method = RequestMethod.POST)
    public void getUserMsg(HttpServletRequest request, HttpServletResponse response) {
        HttpResContent<DingtalkUser> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("获取当前登陆人信息");
        try {
            String userId = RedisUtils.getInstance().getUserId(request);
            DingtalkUser dingtalkUser = dingtalkUserMapper.selectByPrimaryKey(userId);
            SysUser user = sysUserMapper.getByUserId(userId);
            List<String> permissions = JwtTokenUtil.getRolesFromRequest(request);
            DingtalkUser res = new DingtalkUser();
            res.setPermissions(permissions);
            res.setUserId(user.getUserId());
            res.setUserName(user.getUserName());
            res.setMobile(user.getMobile());
            res.setIfSystemUser(user.getIfSysUser());
            if (dingtalkUser != null) {
                res.setAvatar(dingtalkUser.getAvatar());
            }
            if (StringUtils.isEmpty(user.getUserPassword())) {
                res.setIfHasPassword(false);
            } else {
                res.setIfHasPassword(true);
            }
            List<SysUserBindInfo> bindInfos = sysUserBindInfoMapper.listByUserId(userId);
            if (CollectionUtils.isEmpty(bindInfos)) {
                res.setIfBindParent(false);
            } else {
                res.setIfBindParent(true);
            }
            saveSuccessMsgAndData(hrc, res);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/get_by_userAccount.do",method = RequestMethod.POST)
    public void getByuserAccount(HttpServletRequest request, HttpServletResponse response,
                                 String userAccount) {
        HttpResContent<SysUser> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("获取用户");
        try {
            SysUser user = sysUserMapper.getByUserAccount(userAccount);
            saveSuccessMsgAndData(hrc, user);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/get_user_by_deptId.do",method = RequestMethod.POST)
    public void getUserByDeptId(HttpServletRequest request,
                                HttpServletResponse response,
                                Long deptId,
                                String query,
                                Boolean ifExternalUser,
                                Integer page,
                                Integer rows) {
        HttpResContent<PageData> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("获取部门用户");
        try {
            String userAccount = JwtTokenUtil.getUserAccountFromRequset(request);
            loadUserPermissionService.loadUserDataPermission(userAccount);
            List<Long> deptIdUp = new ArrayList<>();
            if (deptId != null) {
                deptIdUp = deptService.getChildDeptIds(deptId);
            }
            //数据权限
            List<String> dataPermissionEmployee = RedisUtils.getInstance().getDataPermissionEmployee(request);
            PageData pageData = sysUserService.getUserByDeptIdsAndCreateUser(deptIdUp, dataPermissionEmployee, query, ifExternalUser, page, rows);
            List<JSONObject> retList = formartUserList(pageData.getData());
            pageData.setData(retList);
            saveSuccessMsgAndData(hrc, pageData);
        } catch (Exception e) {
            e.printStackTrace();
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/save.do",method = RequestMethod.POST)
    public void save(HttpServletRequest request,
                     HttpServletResponse response,
                     Long deptId,
                     String userAccount,
                     String userName,
                     Integer[] roleIds,
                     Integer[] subjectIds) {
        HttpResContent<Boolean> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("外部人员保存");
        try {
            String account = JwtTokenUtil.getUserAccountFromRequset(request);
            String currentUserId = RedisUtils.getInstance().getUserId(account);
            SysUser user = new SysUser();
            user.setUserId(UuidUtil.getUUID());
            user.setUserAccount(userAccount);
            user.setUserName(userName);
            user.setMobile(userAccount);
            user.setCreateUserId(currentUserId);
            user.setCreateTime(new Date());
            user.setIfFromDingtalk(false);
            user.setIfActive(true);
            user.setIfDelete(false);
            user.setIfSysUser(true);
            user.setUserPassword(PasswordUtil.getPassword());
            if (sysUserService.selectUserIfExistByAccount(userAccount)) {
                throw new Exception("该电话号码已存在");
            }
            List<Integer> subjectIdList = new ArrayList();
            if (subjectIds != null) {
                subjectIdList = Arrays.asList(subjectIds);
            }
            sysUserService.save(user, deptId, Arrays.asList(roleIds), subjectIdList);

            saveSuccessMsgAndData(hrc, true);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/delete.do",method = RequestMethod.POST)
    public void delete(HttpServletRequest request,
                       HttpServletResponse response,
                       String userId) {
        HttpResContent<Boolean> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("外部人员删除");
        try {
            sysUserService.delete(userId);
            saveSuccessMsgAndData(hrc, true);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/update_user_name.do",method = RequestMethod.POST)
    public void updateNickName(HttpServletRequest request,
                               HttpServletResponse response,
                               String userId, String userName) {
        HttpResContent<Boolean> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("外部人员修改昵称");
        try {
            SysUser user = new SysUser();
            user.setUserId(userId);
            user.setUserName(userName);
            sysUserMapper.updateByPrimaryKeySelective(user);
            saveSuccessMsgAndData(hrc, true);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/update_user_mobile.do",method = RequestMethod.POST)
    public void updateMobile(HttpServletRequest request,
                             HttpServletResponse response,
                             String userId, String mobile) {
        HttpResContent<Boolean> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("外部人员修改手机号");
        try {
            SysUser user = new SysUser();
            user.setUserId(userId);
            user.setMobile(mobile);
            sysUserMapper.updateByPrimaryKeySelective(user);
            saveSuccessMsgAndData(hrc, true);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/search_user.do",method = RequestMethod.POST)
    public void SearchUser(HttpServletRequest request,
                           HttpServletResponse response,
                           String query,
                           Boolean ifExternalUser) {
        HttpResContent<List<JSONObject>> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("员工列表搜索");
        try {
            //数据权限
            List<String> dataPermissionEmployee = RedisUtils.getInstance().getDataPermissionEmployee(request);
            List<SysUserAdapter> users = sysUserService.getUserByUserNameOrAccount(query, ifExternalUser);
            //交集
            List<SysUserAdapter> intersection = users.stream().filter(s -> dataPermissionEmployee.contains(s.getUserId())).collect(Collectors.toList());
            List<JSONObject> retList = formartUserList(intersection);
            saveSuccessMsgAndData(hrc, retList);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }
    @RequestMapping(value = "/get_user_from_system.do",method = RequestMethod.POST)
    public void getUserFromSystem(HttpServletRequest request,
                           HttpServletResponse response) {
        HttpResContent<List<SelectBean>> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("员工列表搜索");
        try {
            List<SelectBean> res = sysUserService.getUserFromSysten();
            saveSuccessMsgAndData(hrc, res);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }

    private List<JSONObject> formartUserList(List<SysUserAdapter> users) {
        List<JSONObject> retList = BJsonUtil.parseArray(users, JSONObject.class);
        for (int i = 0; i < users.size(); i++) {
            SysUserAdapter sysUser = users.get(i);
            JSONObject obj = retList.get(i);
            List<Integer> roleIdList = new ArrayList<>();
            List<String> nameList = new ArrayList<>();
            List<SysRole> roles = sysUser.getRoles();
            if (roles != null) {
                for (SysRole s : roles) {
                    roleIdList.add(s.getId());
                    nameList.add(s.getName());
                }
            }
            obj.put(KEY_ROLE_ID_LIST, roleIdList);
            obj.put(KEY_NAME_LIST, StringUtils.join(nameList, ","));
            List<SysSubject> subjects = sysUser.getSubjects();
            List<Integer> subjectIds = new ArrayList<>();
            List<String> subjectNameList = new ArrayList<>();
            if (subjects != null) {
                for (SysSubject s : subjects) {
                    subjectIds.add(s.getId());
                    subjectNameList.add(s.getSubjectName());
                }
            }
            obj.put(KEY_SUBJECT_ID_LIST, subjectIds);
            obj.put(KEY_SUBJECT_NAME_LIST, StringUtils.join(subjectNameList, ","));
        }
        return retList;
    }
}
